<template>
  <div class="dashboard">
    <div class="page-header">
      <h2 class="page-title">仪表盘</h2>
      <p class="page-subtitle">欢迎回来，查看您的资产概览</p>
    </div>
    
    <el-row :gutter="24">
      <!-- 总资产 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="8">
        <el-card class="stat-card stat-card-primary" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon-wrapper">
              <div class="stat-icon stat-icon-primary">
                <el-icon><Wallet /></el-icon>
              </div>
            </div>
            <div class="stat-info">
              <div class="stat-label">总资产 (USDT)</div>
              <div class="stat-value">{{ formatBalance(totalBalance) }}</div>
              <div class="stat-change">
                <el-icon><TrendCharts /></el-icon>
                <span>总资产</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 今日充值 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="8">
        <el-card class="stat-card stat-card-success" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon-wrapper">
              <div class="stat-icon stat-icon-success">
                <el-icon><Plus /></el-icon>
              </div>
            </div>
            <div class="stat-info">
              <div class="stat-label">今日充值</div>
              <div class="stat-value">{{ formatBalance(todayDeposit) }}</div>
              <div class="stat-change positive">
                <el-icon><ArrowUp /></el-icon>
                <span>今日收入</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 今日提现 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="8">
        <el-card class="stat-card stat-card-warning" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon-wrapper">
              <div class="stat-icon stat-icon-warning">
                <el-icon><Download /></el-icon>
              </div>
            </div>
            <div class="stat-info">
              <div class="stat-label">今日提现</div>
              <div class="stat-value">{{ formatBalance(todayWithdraw) }}</div>
              <div class="stat-change negative">
                <el-icon><ArrowDown /></el-icon>
                <span>今日支出</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="24" style="margin-top: 24px">
      <!-- 最近交易 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="24">
        <el-card class="transactions-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="card-title">
                <el-icon class="title-icon"><List /></el-icon>
                <span>最近交易</span>
              </div>
              <el-button
                type="primary"
                link
                @click="$router.push('/transactions')"
              >
                查看全部
                <el-icon><Right /></el-icon>
              </el-button>
            </div>
          </template>
          <el-table 
            :data="recentTransactions" 
            style="width: 100%"
            :empty-text="'暂无交易记录'"
            v-loading="loading"
          >
            <el-table-column prop="txId" label="交易ID" width="200">
              <template #default="{ row }">
                <span class="tx-id">{{ formatTxId(row.txId) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getTypeTagType(row.type)" effect="dark">
                  {{ getTypeLabel(row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="150">
              <template #default="{ row }">
                <span :class="['amount', getAmountClass(row.type)]">
                  {{ getAmountPrefix(row.type) }}{{ formatBalance(row.amount) }} {{ row.currency }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)" effect="plain">
                  {{ getStatusLabel(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="时间" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="$router.push({ path: '/transactions', query: { txId: row.txId } })"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="recentTransactions.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无交易记录" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Wallet, Plus, Download, List, Right, TrendCharts, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { walletApi } from '../api/wallet'

const totalBalance = ref(0)
const todayDeposit = ref(0)
const todayWithdraw = ref(0)
const recentTransactions = ref([])
const loading = ref(false)
const usdtDecimals = ref(6) // 默认6位小数

onMounted(async () => {
  await loadData()
})

const loadData = async () => {
  loading.value = true
  try {
    // 获取余额
    const balance = await walletApi.getBalance()
    totalBalance.value = balance.total || 0
    todayDeposit.value = balance.todayDeposit || 0
    todayWithdraw.value = balance.todayWithdraw || 0
    // 使用后端返回的精度，如果没有则使用默认值6
    usdtDecimals.value = balance.usdtDecimals || 6
    
    // 获取最近交易
    const transactions = await walletApi.getTransactions({ pageSize: 5 })
    recentTransactions.value = transactions.list || []
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const formatBalance = (value: number) => {
  if (value === null || value === undefined || isNaN(value)) {
    return '0.000000'
  }
  return value.toFixed(usdtDecimals.value)
}

const getTypeLabel = (type: string) => {
  const map: Record<string, string> = {
    deposit: '充值',
    withdraw: '提现',
    transfer: '转账'
  }
  return map[type] || type
}

const getTypeTagType = (type: string) => {
  const map: Record<string, string> = {
    deposit: 'success',
    withdraw: 'warning',
    transfer: 'info'
  }
  return map[type] || ''
}

const getStatusLabel = (status: string) => {
  const map: Record<string, string> = {
    pending: '处理中',
    confirmed: '已确认',
    failed: '失败'
  }
  return map[status] || status
}

const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    confirmed: 'success',
    failed: 'danger'
  }
  return map[status] || ''
}

const formatTxId = (txId: string) => {
  if (!txId) return '-'
  if (txId.length > 16) {
    return txId.substring(0, 8) + '...' + txId.substring(txId.length - 8)
  }
  return txId
}

const getAmountPrefix = (type: string) => {
  const map: Record<string, string> = {
    deposit: '+',
    withdraw: '-',
    transfer: ''
  }
  return map[type] || ''
}

const getAmountClass = (type: string) => {
  const map: Record<string, string> = {
    deposit: 'amount-positive',
    withdraw: 'amount-negative',
    transfer: 'amount-neutral'
  }
  return map[type] || ''
}
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.stat-card {
  margin-bottom: 0;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon-wrapper {
  flex-shrink: 0;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-icon-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon-success {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.stat-icon-warning {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-info {
  flex: 1;
  min-width: 0;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1.2;
}

.stat-change {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.stat-change.positive {
  color: #67c23a;
}

.stat-change.negative {
  color: #f56c6c;
}

.transactions-card {
  margin-top: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.title-icon {
  font-size: 18px;
  color: #409eff;
}

.tx-id {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  color: #606266;
}

.amount {
  font-weight: 600;
  font-size: 14px;
}

.amount-positive {
  color: #67c23a;
}

.amount-negative {
  color: #f56c6c;
}

.amount-neutral {
  color: #606266;
}

.empty-state {
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stat-value {
    font-size: 24px;
  }
  
  .stat-icon {
    width: 56px;
    height: 56px;
    font-size: 24px;
  }
  
  .stat-content {
    gap: 16px;
  }
}
</style>

